<template>
  <div class="page-container">
    <div class="const-info-box">
      <a-descriptions :align="{ label: 'right' }">
        <a-descriptions-item label="车辆费用单号">{{ feeDetail?.businesCode }}</a-descriptions-item>
        <a-descriptions-item label="应付总额">{{ feeDetail?.carInPayAmount }} 元</a-descriptions-item>
        <a-descriptions-item label="已付金额">{{ feeDetail?.carPayAmount }} 元</a-descriptions-item>
        <a-descriptions-item label="剩余应付金额">{{ feeDetail?.carPayNotAmount }} 元</a-descriptions-item>
        <a-descriptions-item label="应收总额">{{ feeDetail?.carInFeeAmount }} 元</a-descriptions-item>
        <a-descriptions-item label="已收金额">{{ feeDetail?.carReceivedAmount }} 元</a-descriptions-item>
        <a-descriptions-item label="剩余应收金额">{{ feeDetail?.carReceivedNotAmount }} 元</a-descriptions-item>
        <a-descriptions-item :label="feeDetail?.purchaseFeeType == 1 ? '车辆购置费总额' : '车辆借入总额'">
          {{ feeDetail?.purchaseTotalFee }} 元
        </a-descriptions-item>
      </a-descriptions>
      <a-alert class="a-alert">
        <template #title>
          <div class="alert-title">请注意：</div>
        </template>
        <div class="alert-item">1.【车辆购置费】【调车单】需按分期顺序连续确认账单，不支持跳期确认账单 </div>
        <div class="alert-item">2.当收付款对应的供应商不同时，不允许批量结算费用</div>
      </a-alert>
      <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadCompulsoryData" @reset="handleReset" />
      <table-index
        class="insure-card-table"
        :table="tableCompulsory"
        :selectedKeys="selectedRowKeys"
        @selection-change="selectionChange"
        @loadData="loadCompulsoryData"
      >
        <template #expand-icon="{ expanded, record }">
          <!-- 57车辆购置补充费 61 借调附加费 -->
          <span v-if="record.feeNameId == 57 || record.feeNameId == 61">
            <icon-plus-circle class="icon-custom" v-if="!expanded" />
            <icon-minus-circle class="icon-custom" v-else />
          </span>
        </template>
        <template #feeName="{ record }">
          <span
            >{{
              record.feeNameId == 57 ||
              record.feeNameId == 61 ||
              record.feeCategory == 5 ||
              (record.feeCategory == 6 && record.installment == 0)
                ? ''
                : record.feeCategoryName + '-'
            }}{{ record.feeName }}</span
          >
        </template>
      </table-index>
    </div>
  </div>
  <confirmCost ref="confirmCostRef" @confirm="costConfirm" />
  <modifyCost ref="modifyCostRef" @confirm="costConfirm" />
</template>

<script setup lang="ts">
  import { useTable } from '@/hooks/table'
  import { ref, reactive, computed, onMounted } from 'vue'
  import { carPurchaseDetail, mergeConfirmValidate } from '@/api/asset/car'
  import { Message } from '@arco-design/web-vue'
  import confirmCost from '../../confirm-cost.vue'
  import modifyCost from '../../modify-cost.vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  const dict = usePageDict('carAssetFeeDict')
  const route = useRoute()
  const params = route.params
  const query = route.query

  const dueDate = computed(() => {
    if (query.date && query.date != 'undefined') {
      const [start, end] = JSON.parse(query.date as string)
      return [dayjs(start).format('YYYY-MM-DD'), dayjs(end).endOf('month').format('YYYY-MM-DD')]
    }
    return []
  })

  const modifyCostRef = ref()
  const confirmCostRef = ref()
  const queryParam = reactive<any>({})
  // 查询条件
  const searchList = [
    { label: '收支类型', prop: 'costType', type: 'a-select', options: dict.costTypeEnum },
    { label: '费用状态', prop: 'feeStatus', type: 'a-select', options: dict.feeStatusEnum },
    {
      label: '应结日期',
      prop: 'dueTime',
      type: 'i-range-picker',
      change: (value: any) => {
        if (value) {
          queryParam.dueStartDate = dayjs(value[0]).format('YYYY-MM-DD 00:00:00')
          queryParam.dueEndDate = dayjs(value[1]).format('YYYY-MM-DD 23:59:59')
        } else {
          queryParam.dueStartDate = undefined
          queryParam.dueEndDate = undefined
        }
      },
    },
  ]
  /**
   * 根据路由名称获取权限字符串
   * 此函数用于根据当前路由名称判断是否返回特定的权限字符串
   * 主要用于控制在特定路由下不显示权限字符串
   *
   * @param {string} permissionStr - 传入的权限字符串
   * @returns {string} 根据路由名称决定是否返回权限字符串，对于特定路由返回空字符串
   */
  const getPermission = (permissionStr: string) => {
    // 特殊处理'CarPurchaseConfirmCost'路由，不显示权限字符串
    if (route.name == 'CarPurchaseConfirmCost') {
      return ''
    } else {
      // 对于其他路由，直接返回传入的权限字符串
      return permissionStr
    }
  }
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'feeName', slotName: 'feeName', width: 120, fixed: 'left' },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 90 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 90 },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元', width: 110 },
      { title: '实结金额', dataIndex: 'payAmount', unit: '元', width: 110 },
      { title: '待结金额', dataIndex: 'outstandingAmount', unit: '元', width: 110 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 120 },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      {
        title: '应结日期',
        dataIndex: 'dueDate',
        width: 120,
        // titleTooltipContent: 'a.分期车辆的购置费取自【费用信息】中设置的应付款日。b.不分期车辆的购置费取自费用的生成时间。',
      },
      { title: '收支方式', dataIndex: 'payTypeName', width: 100 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '实结时间', dataIndex: 'payTime', width: 170 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 170 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 100 },
      { title: '费用备注', dataIndex: 'remark', width: 120, ellipsis: true },
      { title: '结算备注', dataIndex: 'settlementRemark', width: 120, ellipsis: true },
    ],
    buttons: [
      {
        type: 'primary',
        label: '批量结算',
        permission: getPermission('svms:asstes:car:car-model.cost.mergeConfirm'),
        method: () => {
          if (selectedRowKeys.value.length == 0) {
            Message.error('请选择需要批量结算的费用')
            return
          }
          // 批量结算时，传值选中项首项的supplierType、supplierName
          let changeId = selectedRowKeys.value[0]
          let tableData = tableCompulsory.dataList
          let changeObj = tableData.find((i: any) => i.id == changeId)

          let supplierType = changeObj.supplierType
          let supplierName = changeObj.supplierName

          mergeConfirmValidate({ businesId: businesId.value, idList: selectedRowKeys.value, installmentList: installmentIds.value }).then(
            (res: any) => {
              if (res.result) {
                confirmCostRef.value.open({
                  idList: selectedRowKeys.value,
                  carId: params.id,
                  supplierType: supplierType,
                  supplierName: supplierName,
                  title: `批量结算-${feeDetail.value.carLicenseNo}`,
                })
              }
            }
          )
        },
      },
    ],
    operates: [
      {
        label: '结算',
        show: (record: any) => record.feeStatus === 0 || record.feeStatus === 3 || record.feeStatus === 5,
        permission: getPermission('svms:asstes:car:car-model.cost.confirmCost'),
        method: (record: any) => {
          console.log(record, 'record')

          if (!record.feeChecke) {
            Message.error('不支持跨期结算')
            return
          }
          confirmCostRef.value.open({
            idList: [record.id],
            supplierType: record.supplierType,
            supplierName: record.supplierName,
            carId: params.id,
            title: `结算-${feeDetail.value.carLicenseNo}`,
          })
        },
      },
      {
        label: '修改费用',
        show: (record: any) => record.feeStatus === 0 || record.feeStatus === 3 || record.feeStatus === 5,
        permission: getPermission('svms:asstes:car:car-model.cost.editCost'),
        method: (record: any) => {
          //  feeCategory 0-购置费 6-借调费 5-其他费用
          //  feeNameId 59-借出  61-借调附加费 58-跨门店借调费
          if (record.feeCategory === 5) {
            modifyCostRef.value.open({
              id: record.id,
              feeCategory: record.feeCategory,
              installment: record.installment,
              businesId: record.businesId,
              businesCode: feeDetail.value.businesCode,
              carId: params.id,
              title: `修改费用-${feeDetail.value.carLicenseNo}`,
            })
          } else if (record.feeNameId == 61 || record.feeNameId == 58) {
            modifyCostRef.value.open({
              id: record.id,
              feeNameId: record.feeNameId,
              feeCategory: record.feeCategory,
              installment: record.installment,
              businesId: record.businesId,
              businesCode: feeDetail.value.businesCode,
              carId: record.carId,
              title: `修改费用-${feeDetail.value.carLicenseNo}`,
            })
          } else {
            modifyCostRef.value.open({
              id: record.businesId,
              _id: record.id,
              feeNameId: record.feeNameId,
              feeCategory: record.feeCategory,
              installment: record.installment,
              businesId: record.businesId,
              businesCode: feeDetail.value.businesCode,
              carId: params.id,
              title: `修改费用-${feeDetail.value.carLicenseNo}`,
            })
          }
        },
      },
    ],
    dataList: [],
  })

  // 字段处理
  const tabletolist = (list: any[] = []) => {
    list.forEach((el: any) => {
      el.mtype = 'MENU'
      el.level = 1
      el.checked = false
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl: any) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeNameId = el.feeNameId
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
          pl.disabled = true
          pl.isClass = true
        })
      } else {
        return false
      }
    })
    return list
  }

  const feeDetail = ref()

  const loadCompulsoryData = () => {
    tableCompulsory.dataList = []
    var param = {
      carId: params.id,
      feeCategoryList: [0, 5, 6],
      dueStartDate: queryParam.dueStartDate,
      dueEndDate: queryParam.dueEndDate,
    }
    tableCompulsory.tableLoading = true
    carPurchaseDetail(param)
      .then((res: any) => {
        feeDetail.value = res.result
        const result = res.result
        const dataOne: any[] = []
        if (result.carAssetFeeList && result.carAssetFeeList.length) {
          result.carAssetFeeList.forEach((i: any) => {
            if (
              (queryParam.feeType == undefined || queryParam.feeType === i.feeType) &&
              (queryParam.costType == undefined || queryParam.costType === i.costType) &&
              (queryParam.feeStatus == undefined || queryParam.feeStatus === i.feeStatus)
            ) {
              dataOne.push(i)
            }
          })
        }
        const carAssetFeeList = dataOne

        setTimeout(() => {
          tableCompulsory.dataList = tabletolist(carAssetFeeList)

          // 获取当前日期的23:59:59
          const currentDate = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
          selectedRowKeys.value = []
          tableCompulsory.dataList.map((it: any) => {
            const isFeeStatusValid = [0, 3, 5].includes(it.feeStatus)
            // 应结日期取消时分秒
            it.dueDate = dayjs(it.dueDate).format('YYYY-MM-DD')
            // 判断 dueDate 是否小于或等于当前日期
            const isDueDateValid = it.dueDate <= currentDate
            if (isFeeStatusValid && isDueDateValid) {
              selectedRowKeys.value.push(it.id)
            }
            // 根据判断条件设置 disabled
            it.disabled = !isFeeStatusValid
          })
          renderSelectId()
        }, 0)
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }

  const selectedRowKeys = ref([])
  // 业务单ID
  const businesId = ref('')
  // 期数ID
  const installmentIds = ref<Array<number | string>>([])
  const selectionChange = (e) => {
    selectedRowKeys.value = e
    renderSelectId()
  }
  const renderSelectId = () => {
    // 清空之前的值
    businesId.value = '' // 重新赋值空字符串
    installmentIds.value = [] // 清空 installmentIds 数组

    // 遍历 dataList，检查 id 是否在 selectedRowKeys.value 中
    tableCompulsory.dataList.forEach((record) => {
      const index = selectedRowKeys.value.indexOf(record.id)
      if (index !== -1) {
        // 如果 id 匹配，且 businesId.value 为空，就赋值 businesId.value 为第一个匹配项的 businesId
        if (businesId.value === '') {
          businesId.value = record.businesId // 只取第一个匹配的 businesId
        }
        // 添加 payableNum 到 installmentIds.value
        installmentIds.value.push(record.payableNum)
      }
    })
  }
  const costConfirm = () => {
    loadCompulsoryData()
    tableCompulsory.dataList.forEach((el: any) => {
      el.checked = false
    })
    selectedRowKeys.value = []
    installmentIds.value = []
    businesId.value = ''
  }

  const getRowClassName = (record: any) => {
    return record.isClass ? 'arco-table-tr-expand' : ''
  }

  onMounted(() => {
    if (dueDate.value.length > 0) {
      queryParam.dueTime = dueDate.value
      queryParam.dueStartDate = dayjs(dueDate.value[0]).format('YYYY-MM-DD 00:00:00')
      queryParam.dueEndDate = dayjs(dueDate.value[1]).format('YYYY-MM-DD 23:59:59')
    }
    loadCompulsoryData()
  })
</script>

<style lang="less" scoped>
  .page-container {
    padding-top: 4px;
  }
  .a-alert,
  .alert-title {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
  }

  .a-alert {
    margin-top: 12px;
    margin-bottom: 20px;
  }
  .check-box {
    margin-top: 4px;
  }

  :deep(.arco-table .arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .icon-custom {
    color: #0256ff;
    font-size: 20px;
  }
</style>
